#include <iostream>
#include "list.h"

using namespace std;

List::~List(void)
{
	for(int i = size();i!=0;i--)
	{
		head_del();	
	}
}

//头添加
void List::head_add(TYPE data)
{
	Node* node = new Node(data);
	node->next = head;
	head = node;
}
//尾添加
void List::tail_add(TYPE data)
{
	Node* node1 =head;
	while(NULL != node1->next)
	{
		node1 = node1->next;
	}
	
	Node* node = new Node(data);
	node1->next = node;
}
//头删除
bool List::head_del(void)
{
	if(0 == size()) return false;
	else if( 1 ==size())
	{
		head=NULL;
	}
	else
	{
		Node* node = head;
		head = node->next;
		delete node;
	}
}
//尾删除
bool List::tail_del(void)
{
	if(1 == size())
	{
		head_del();
		return true;
	}
	else if(0 == size())
	{
		return false;
	}
	else
	{
		Node* node =head;
		while(NULL!=node->next->next)
		{
			node= node->next;
		}
		node->next =NULL;
		delete node->next;
		return true;
	}
}
//求链表长度
size_t List::size(void)
{
	int size=0;
	Node* node = head;
	for(size;NULL != node;node= node->next)
	{
		size++;
	}
	return size;
}

//遍历
void List::show_list(void)
{
	for(Node* node = head;NULL != node;node =node->next)
	{
		cout << node->data << ' ';
		}
		cout << endl;
}

//排序
void List::sort_list(void)
{
	for(Node* i = head;i->next != NULL;i = i->next)
	{
		for(Node* j=i->next;NULL != j;j=j->next)
		{
			if(i->data>j->data)
			{
				TYPE temp=i->data;
				i->data=j->data;
				j->data=temp;
				}
			}
		}
	}
	
//插入
bool List::insert_list(int index , TYPE data)
{
	if(index<0||index >= size())return false;
	if(0 == index)
	{
		head_add(data);
		return true;
		}
	Node* prev=head;
	for(int i=1;i<index-1;i++)
	{
		prev=prev->next;
		}
	Node* node = new Node(data);
	node->next=prev->next;
	prev->next=node;
	return true;
	}

//值删除
bool List::delete_value_list(TYPE data)
{
	if(data == head->data)
	{
		head_del();
		return true;
		}
	Node* prev=head;
	while(NULL != prev->next)
	{
		if(data == prev->next->data)
		{
			Node* node = prev->next;
			prev->next=node->next;
			delete(node);
			return true;
			}
		prev=prev->next;
		}
		return false;
	}
	
//位置删除
bool List::delete_index_list(int index)
{	
	if(index<0||index >= size())return false;
	if(0 == index)
	{
		head_del();
		return true;
		}
	else if(size() == index)
		tail_del();
	else	
	{
		Node* prev=head;
		for(int i=1;i<index-1;i++)
		{
			prev=prev->next;//要删除数据的前一个节点
			}
		Node* node = prev->next;//node就相当于prev之后的节点
		prev->next = node->next;//之后的之后节点与prev链接
		delete(node);;
		return true;
	}
	
}
